import React, {PropTypes}           from 'react';
import {connect}                    from 'react-redux';
import moment                       from 'moment';
import Editor                       from './editors/index';
import {NOTE_UPDATING}              from '../actions/actionTypes';
import {updateNote, switchNoteFromRemote} from '../actions/note';
import Icon                         from './components/icons/index';

import 'moment/locale/zh-cn';
moment.locale('zh-cn');

function mapStateToProps(state) {
  return {
    currentNote: state.note.current || {
      title: '',
      content: ''
    },
    updating: state.note.type == NOTE_UPDATING
  };
}

export class NotePaper extends React.Component {
  static propTypes = {
    name: PropTypes.string,
    params: PropTypes.object,
    dispatch: PropTypes.func,
    currentNote: PropTypes.object,
    updating: PropTypes.bool,
  };

  constructor(props) {
    super(props);
    this.state = {
      mode: 'inline'
    };
  }

  componentDidMount() {
    this.props.switchNoteFromRemote(this.props.params.noteId);
  }

  componentWillReceiveProps(nextProps) {
    if (this.props.params.noteId != nextProps.params.noteId) {
      this.props.switchNoteFromRemote(nextProps.params.noteId);
    }
  }

  getNote() {
    return this.props.currentNote || {};
  }

  linkState(field) {
    return {
      value: this.getNote()[field],
      onChange: (e)=> {
        let note = this.getNote();
        this.props.updateNote(note._id, e.target.value, note.content);
      }
    }
  }

  handleContentChange(content) {
    let note = this.getNote();
    if (content != note.content) this.props.updateNote(note._id, note.title, content);
  }

  render() {
    let note = this.getNote();
    return (
      <div id="NotePaper">
        <div className="paper-top">
          <input className="title" placeholder="无标题笔记" {...this.linkState('title')}/>
          <span style={{float: 'right', marginRight: '1rem'}}>
            {this.props.updating && <Icon type="ios-compose-outline" style={{marginRight: '1rem'}}/>}
            <date >{moment(note && note.dateUpdated).fromNow()}</date>
          </span>
        </div>
        <div className={`paper-bottom ${this.state.mode}`}>
          <Editor.sim input={note.content}
                      output={this.handleContentChange.bind(this)}/>
        </div>
      </div>
    );
  }
}

export default connect(
  mapStateToProps,
  {switchNoteFromRemote, updateNote}
)(NotePaper)
